var express = require('express');
var router = express.Router();
var path = require("path");

// 获取验证模块
var authorization = require(path.join(process.cwd(), "/modules/authorization"));

// 通过验证模块获取博客管理服务
var artServ = authorization.getService("ArticleService");

// 查询博客列表
router.get("/",
	// 业务逻辑
	function (req, res, next) {
		var conditions = {
			"pagenum": req.query.pagenum,
			"pagesize": req.query.pagesize
		};

		if (req.query.query) {
			conditions["query"] = req.query.query;
		}
		artServ.getAllArticles(
			conditions,
			function (err, result) {
				if (err) return res.sendResult(null, 400, err);
				res.sendResult(result, 200, "获取成功");
			}
		)(req, res, next);
	}
);

// 获取博客信息
router.get("/:id",
	// 参数验证
	function (req, res, next) {
		if (!req.params.id) {
			return res.sendResult(null, 400, "博客ID不能为空");
		}
		if (isNaN(parseInt(req.params.id))) return res.sendResult(null, 400, "博客ID必须是数字");
		next();
	},
	function (req, res, next) {
		artServ.getArticle(req.params.id, function (err, article) {
			if (err) return res.sendResult(null, 400, err);
			res.sendResult(article, 200, "获取成功");
		})(req, res, next);
	}
);
router.post("/",
	function (req, res, next) {
		if (!req.body.title) {
			return res.sendRcontentesult(null, 400, "博客标题不能为空");
		}
		if (!req.body.content) {
			return res.sendResult(null, 400, "博客内容不能为空");
		}
		next()
	},
	function (req, res, next) {
		var params = req.body;
		artServ.createdArticle(params, function (err, newGood) {
			if (err) return res.sendResult(null, 400, err);
			res.sendResult(newGood, 201, "发布博客成功");
		})(req, res, next);
	}
);


module.exports = router;